import { ref, reactive, computed } from 'vue'

/**
 * 通用页面级 CRUD 组合式函数
 * 
 * @param {Object} options
 * @param {Function} options.fetchList - (query)=> Promise<{ list: any[], total: number }>
 * @param {Function} options.createItem - (data)=> Promise<any>
 * @param {Function} options.updateItem - (id, data)=> Promise<any>
 * @param {Function} options.deleteItem - (id)=> Promise<any>
 * @param {Function} [options.batchDelete] - (ids: any[])=> Promise<any>
 * @param {string} [options.idKey='id'] - 主键字段
 * @param {Object} [options.defaultQuery] - 初始查询条件
 * @returns CRUD 页面所需的全部状态与方法
 */
export function usePageCrud(options) {
    const {
        fetchList,
        createItem,
        updateItem,
        deleteItem,
        batchDelete,
        idKey = 'id',
        defaultQuery = {}
    } = options

    // 查询与分页
    const query = reactive({ ...defaultQuery })
    const pagination = reactive({ page: 1, pageSize: 10, total: 0 })

    // 列表与选择
    const loading = ref(false)
    const list = ref([])
    const selection = ref([])

    // 弹窗表单
    const dialogVisible = ref(false)
    const editing = ref(null)
    const formModel = ref({})
    const formLoading = ref(false)

    const isEdit = computed(() => !!editing.value)

    async function getList() {
        loading.value = true
        try {
            const res = await fetchList({
                ...query,
                page: pagination.page,
                pageSize: pagination.pageSize
            })
            list.value = Array.isArray(res.list) ? res.list : []
            pagination.total = Number(res.total || 0)
        } finally {
            loading.value = false
        }
    }

    function resetQuery() {
        Object.keys(query).forEach(k => delete query[k])
        Object.assign(query, { ...defaultQuery })
        pagination.page = 1
        getList()
    }

    function openCreate(initial = {}) {
        editing.value = null
        formModel.value = { ...initial }
        dialogVisible.value = true
    }

    function openEdit(row) {
        editing.value = row
        formModel.value = { ...row }
        dialogVisible.value = true
    }

    async function submitForm() {
        formLoading.value = true
        try {
            if (isEdit.value) {
                const id = formModel.value[idKey]
                await updateItem(id, { ...formModel.value })
            } else {
                await createItem({ ...formModel.value })
            }
            dialogVisible.value = false
            await getList()
        } finally {
            formLoading.value = false
        }
    }

    async function removeRow(row) {
        const id = row?.[idKey]
        if (id == null) return
        await deleteItem(id)
        await getList()
    }

    async function removeSelected() {
        const ids = selection.value.map(v => v[idKey])
        if (!ids.length) return
        if (batchDelete) {
            await batchDelete(ids)
        } else {
            // 顺序删除（简化实现）
            for (const id of ids) {
                await deleteItem(id)
            }
        }
        selection.value = []
        await getList()
    }

    function onSelectionChange(rows) {
        selection.value = rows || []
    }

    function onPageChange(page) {
        pagination.page = page
        getList()
    }

    function onPageSizeChange(size) {
        pagination.pageSize = size
        pagination.page = 1
        getList()
    }

    return {
        // 状态
        query,
        pagination,
        list,
        loading,
        selection,
        dialogVisible,
        formModel,
        formLoading,
        editing,
        isEdit,
        // 行为
        getList,
        resetQuery,
        openCreate,
        openEdit,
        submitForm,
        removeRow,
        removeSelected,
        onSelectionChange,
        onPageChange,
        onPageSizeChange
    }
} 